/**
 * @description: excel导出
 */
import * as ExcelJS from "exceljs";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import { fileToBase64, base64ToBlob, base64ToBuffer, arrayToBase64, isBase64 } from "@/utils/util";
import ACrypto from "@/utils/crypto";
import http from "@/api"; //axios封装
import moment from "moment";
export class Excel {
  dynamicStore: any;
  dictionryStore: any;
  catalogStore: any;
  // 报表配置
  excelConfig: any;
  //用来判断是否是模板类型
  ift: Boolean;
  index: number;
  combinedJSON: any;
  constructor(data: any, ownData: any[], fatherData: any, childData: any[]) {
    this.dynamicStore = useDynamicStore();
    this.dictionryStore = useDictionryStore();
    this.catalogStore = useCatalogStore();
    // 配置数据
    this.excelConfig = data;
    //用来判断是否是模板类型
    this.ift = true;
    // 用来判断获取到哪个层级的数据
    this.index = 0;
    // 数据层级
    this.combinedJSON = {
      // 本身数据
      own: ownData,
      // 父级数据
      parent: fatherData,
      // 子级数据
      child: childData,
      //字典数据
      dictionary: this.dictionryStore.getDictionaryObj
    };
  }
  download = async () => {
    // 表格配置
    const config = JSON.parse(this.excelConfig.RM_Config);
    // 获取配置中的行数
    const configRows = config.Rows;
    // 获取配置中的列数
    const configColumns = config.Columns;
    // 排序规则
    const sortRule = "id.asc";
    // 根据index获取不同的层级数据
    if (config.DataSource === "本表") {
      this.index = 0;
    } else if (config.DataSource === "本表父级") {
      this.index = 1;
    } else if (config.DataSource === "本表子级") {
      this.index = 2;
    }
    // 拿到指定层级的数据
    const dataSource = Object.values(this.combinedJSON)[this.index] as any[];
    // 规则拆分
    const sortRulesArray = sortRule.split(",");
    // 使用Array.reduce来依次应用多个排序规则
    dataSource.sort((a, b) => {
      console.log(111);
      return sortRulesArray.reduce((result, rule) => {
        console.log(result, rule);

        if (result !== 0) {
          return result;
        }
        const sortOrder = rule.endsWith(".desc") ? -1 : 1;
        const key = rule.replace(/\.asc|\.desc/, "");
        const aValue = a[key];
        const bValue = b[key];
        return aValue > bValue ? sortOrder : aValue < bValue ? -sortOrder : 0;
      }, 0);
    });
  };
}
